package com.hboxs.asl.qcloudLVB.controller.app;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.qcloudLVB.Conf;
import com.hboxs.asl.qcloudLVB.Constants;
import com.hboxs.asl.qcloudLVB.entity.Live;
import com.hboxs.asl.qcloudLVB.service.LiveService;
import com.hboxs.asl.qcloudLVB.util.IpUtils;
import com.hboxs.asl.qcloudLVB.util.QcloudDateUtils;
import com.hboxs.asl.service.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Set;
import java.util.UUID;

/**
 * Created by xxx on 10/12/2016.
 * <p>
 * Controller -- 前端接口
 * <p>
 */
@Controller(value = "appLiveMemberController")
@RequestMapping(value = "/app/m/live")
public final class LiveMemberController extends BaseController {

    protected Logger logger = Logger.getLogger(getClass());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "liveServiceImpl")
    private LiveService liveService;
    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "courseTradeServiceImpl")
    private CourseTradeService courseTradeService;
    @Resource(name = "liveGiftServiceImpl")
    private LiveGiftService liveGiftService;
    @Resource(name = "liveGiftTradeServiceImpl")
    private LiveGiftTradeService liveGiftTradeService;
    @Resource(name = "globalConfigServiceImpl")
    private GlobalConfigService globalConfigService;
    @Resource(name = "financialRecordServiceImpl")
    private FinancialRecordService financialRecordService;

    /**
     * 录播添加人数
     * @param liveId
     * @return
     */
    @RequestMapping(value = "/add_watchMember", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage addWatchMember(Long liveId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Live live = liveService.find(liveId);
            if (live == null) {
                return JsonMessage.error("课程已下架");
            }
            //获取观看过的会员
            Set<Member> memberSet = live.getWatchedMembers();
            if (!memberSet.contains(member)) {
                if (live.getAnchor() != null) {
                    //当前用户为主播不添加
                    if (live.getAnchor().getId() != member.getId()) {
                        memberSet.add(member);
                        live.setWatchedMembers(memberSet);
                        liveService.save(live);
                    }
                }
            }
            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 创建直播，传title,cover
     *
     * @param live 直播对象 (老师)
     * @return json
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public
    @ResponseBody
    Object create(HttpServletRequest request, Live live, Long courseId, String touristId, Long connectLiveId) {

        //主播
        Member anchor = memberService.getCurrentByToken();
        if (!StringUtils.isEmpty(touristId)) {
            anchor.setTouristId(touristId);
            memberService.update(anchor);
        }
        //修改课程状态
        Course course = courseService.find(courseId);
        if (course != null) {
            if (course.getCourseType().equals(Course.CourseType.finished)) {
                return JsonMessage.error("课程已经直播结束");
            }
            course.setType(Course.Type.course);
            course.setCourseType(Course.CourseType.live);
            live.setTitle(course.getTitle());
            live.setCover(course.getImageURL());
        }

        live.setIp(IpUtils.getIpAddr(request));
        live.setCourse(course);

        //如果存在直播,将其设置为下线
        liveService.offLive(anchor);

        Live connectLive = liveService.find(connectLiveId);

        Live p_live = liveService.create(live, anchor, connectLive);

        if (p_live == null) {
            return JsonMessage.error("直播创建失败");
        }

        if(course != null) {
            course.setLive(p_live);
            courseService.update(course);
            //TODO 批量修改订单中的课程状态
            courseTradeService.updateBatch(course.getId(), CourseTrade.CourseType.live);
        }

        //拼装推流url
        String pushurl = liveService.getPushUrl(Conf.BIZID, live.getId().toString(), Conf.PUSH_KEY, QcloudDateUtils.getTxTime(Constants.PUSH_TXTIME));
        return JsonMessage.success(
                "notice", globalConfigService.getUniqueness().getNotice(),
                "anchorId", anchor.getId(),
                "avator", anchor.getAvator(),
                "name", anchor.getName(),
                "username", anchor.getUsername(),
                "liveId", p_live.getId(),
                "pushurl", pushurl
        );
    }


    /**
     * 关注主播 (用户端)
     *
     * @param id 直播id
     * @return isfocus ==0 ，成功关注; isfocus ==1 ，取消关注;
     */
    @RequestMapping(value = "/focus", method = RequestMethod.POST)
    public
    @ResponseBody
    Object focus(Long id) {

        Live live = liveService.find(id);

        if (live == null) {
            return JsonMessage.error("直播不存在");
        }

        if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || live.getAnchor() == null) {
            return JsonMessage.error("直播已关闭");
        }

        //主播
        Member anchor = live.getAnchor();
        //会员
        Member member = memberService.getCurrentByToken();

        int isfocus = 1;
        if (member.getFavorAnchors().contains(anchor)) {
            member.getFavorAnchors().remove(anchor);
            isfocus = 0;
        } else {
            member.getFavorAnchors().add(anchor);
        }

        memberService.update(member);

        return JsonMessage.success(isfocus);
    }

    /**
     * 购买礼物
     *
     * @param id       礼物id
     * @param anchorId 主播id
     */
    @RequestMapping(value = "/buyGift", method = RequestMethod.POST)
    public
    @ResponseBody
    Object buyGift(Long id, Long anchorId) {

        Member member = memberService.getCurrentByToken();
        LiveGift liveGift = liveGiftService.find(id);
        Member anchor = memberService.find(anchorId);


        if (liveGift == null) {
            return JsonMessage.error("礼物不存在");
        }

        if (member.getPoint().compareTo(liveGift.getCoin()) < 0) {
            return JsonMessage.error("积分不足");
        }

        String uuid = UUID.randomUUID().toString();
        //TODO 用户积分变化
        member.setPoint(member.getPoint().subtract(liveGift.getCoin()));
        memberService.update(member);

        //TODO 积分转换为余额
        BigDecimal money = liveGift.getCoin().divide(globalConfigService.getUniqueness().getPercentage());
        //TODO 主播余额变化
        anchor.setBalance(anchor.getBalance().add(money));
        //TODO 主播收入
        anchor.setEarnings(anchor.getEarnings().add(money));

        memberService.update(anchor);

        //TODO 主播收入记录
        financialRecordService.incomeLiveGifts(anchor, money);
        //TODO 用户支出记录
        financialRecordService.expenditureLiveGifts(member, money);

        LiveGiftTrade liveGiftTrade = new LiveGiftTrade(uuid, liveGift, liveGift.getCoin(), liveGift.getName(), member, anchor);
        liveGiftTradeService.save(liveGiftTrade);

        return JsonMessage.success();
    }

}